# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-12 12:15
# File     : health.py
# Project  : codebuddy_craft
# Desc     : 健康检查路由

"""
健康检查路由 🏥

提供应用健康状态检查和系统指标监控
"""

import os
import time
import psutil
import platform
from typing import Dict, Any, Optional
from datetime import datetime, timedelta

from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.responses import JSONResponse

from backend.core.settings import settings
from backend.database.connection import health_check as db_health_check
from backend.utils.logger import get_performance_logger

# 创建路由
health_router = APIRouter(tags=["health"])

# 性能日志记录器
perf_logger = get_performance_logger("health")

# 应用启动时间
START_TIME = datetime.now()


@health_router.get("/")
async def health_check(request: Request) -> Dict[str, Any]:
    """健康检查 🏥
    
    检查应用的基本健康状态
    
    Returns:
        健康状态信息
    """
    with perf_logger.start_timer("health_check"):
        # 检查数据库健康状态
        db_status = await db_health_check()
        
        # 计算运行时间
        uptime = datetime.now() - START_TIME
        uptime_seconds = int(uptime.total_seconds())
        
        # 构建健康状态响应
        health_status = {
            "status": "healthy" if db_status["status"] == "healthy" else "unhealthy",
            "timestamp": datetime.now().isoformat(),
            "version": settings.PROJECT_VERSION,
            "environment": settings.ENVIRONMENT,
            "uptime": {
                "seconds": uptime_seconds,
                "formatted": format_uptime(uptime_seconds)
            },
            "database": db_status
        }
        
        # 记录性能指标
        perf_logger.record_metric("health_check_status", 1 if health_status["status"] == "healthy" else 0)
        
        return health_status


@health_router.get("/system")
async def system_info(request: Request) -> Dict[str, Any]:
    """系统信息 ⚙️
    
    获取系统资源使用情况
    
    Returns:
        系统资源信息
    """
    with perf_logger.start_timer("system_info"):
        # 获取系统信息
        cpu_percent = psutil.cpu_percent(interval=0.1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # 获取进程信息
        process = psutil.Process(os.getpid())
        process_memory = process.memory_info()
        
        # 构建系统信息响应
        system_data = {
            "timestamp": datetime.now().isoformat(),
            "hostname": platform.node(),
            "platform": {
                "system": platform.system(),
                "release": platform.release(),
                "version": platform.version(),
                "python": platform.python_version()
            },
            "cpu": {
                "percent": cpu_percent,
                "cores": psutil.cpu_count(logical=False),
                "threads": psutil.cpu_count(logical=True)
            },
            "memory": {
                "total": format_bytes(memory.total),
                "available": format_bytes(memory.available),
                "used": format_bytes(memory.used),
                "percent": memory.percent
            },
            "disk": {
                "total": format_bytes(disk.total),
                "free": format_bytes(disk.free),
                "used": format_bytes(disk.used),
                "percent": disk.percent
            },
            "process": {
                "pid": process.pid,
                "memory_rss": format_bytes(process_memory.rss),
                "memory_vms": format_bytes(process_memory.vms),
                "threads": process.num_threads(),
                "cpu_percent": process.cpu_percent(interval=0.1)
            }
        }
        
        # 记录性能指标
        perf_logger.record_memory_usage("process_memory_mb", process_memory.rss / (1024 * 1024))
        perf_logger.record_metric("process_cpu_percent", process.cpu_percent(interval=0.1), "%")
        
        return system_data


@health_router.get("/metrics")
async def metrics(request: Request) -> Dict[str, Any]:
    """性能指标 📊
    
    获取应用性能指标
    
    Returns:
        性能指标数据
    """
    with perf_logger.start_timer("get_metrics"):
        # 获取数据库连接池状态
        try:
            from backend.database.pool_monitor import get_pool_stats
            pool_stats = get_pool_stats()
        except ImportError:
            pool_stats = {"status": "not_available"}
        
        # 构建性能指标响应
        metrics_data = {
            "timestamp": datetime.now().isoformat(),
            "database_pool": pool_stats,
            "uptime": {
                "seconds": int((datetime.now() - START_TIME).total_seconds()),
                "formatted": format_uptime(int((datetime.now() - START_TIME).total_seconds()))
            }
        }
        
        # 刷新性能指标
        perf_logger.flush_metrics()
        
        return metrics_data


def format_bytes(bytes_value: int) -> str:
    """格式化字节数 📏
    
    Args:
        bytes_value: 字节数
        
    Returns:
        格式化后的字符串
    """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes_value < 1024.0:
            return f"{bytes_value:.2f} {unit}"
        bytes_value /= 1024.0
    return f"{bytes_value:.2f} PB"


def format_uptime(seconds: int) -> str:
    """格式化运行时间 ⏱️
    
    Args:
        seconds: 秒数
        
    Returns:
        格式化后的字符串
    """
    days, remainder = divmod(seconds, 86400)
    hours, remainder = divmod(remainder, 3600)
    minutes, seconds = divmod(remainder, 60)
    
    parts = []
    if days > 0:
        parts.append(f"{days}d")
    if hours > 0 or days > 0:
        parts.append(f"{hours}h")
    if minutes > 0 or hours > 0 or days > 0:
        parts.append(f"{minutes}m")
    parts.append(f"{seconds}s")
    
    return " ".join(parts)